﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace UI
{
    public class WeiXin
    {
        public string HttpPost(string Url, string postDataStr)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
            byte[] data = encoding.GetBytes(postDataStr);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(Url) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return err;
            }
        }
        public void Log(string str)
        {
            string path = HttpContext.Current.Server.MapPath("/log.txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true, System.Text.Encoding.GetEncoding("utf-8"));//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine("=======================" + DateTime.Now + "=======================");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
        }
        /// <summary>
        /// Http方式下载文件
        /// </summary>
        /// <param name="url">http地址</param>
        /// <param name="localfile">本地文件</param>
        /// <returns></returns>
        public bool HttpDownload(string url, string localfile)
        {
            bool flag = false;
            long startPosition = 0; // 上次下载的文件起始位置
            FileStream writeStream; // 写入本地文件流对象
                                    // 判断要下载的文件夹是否存在
            if (File.Exists(localfile))
            {
                writeStream = File.OpenWrite(localfile);             // 存在则打开要下载的文件
                startPosition = writeStream.Length;                  // 获取已经下载的长度
                writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
            }
            else
            {
                writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
                startPosition = 0;
            }
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接
                if (startPosition > 0)
                {
                    myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
                }
                Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流
                byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
                int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次
                while (contentSize > 0)// 如果读取长度大于零则继续读
                {
                    writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                    contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
                }//关闭流
                writeStream.Close();
                readStream.Close();
                flag = true;        //返回true下载成功
            }
            catch (Exception)
            {
                writeStream.Close();
                flag = false;       //返回false下载失败
            }
            return flag;
        }
        public string FindUrl(string area, string file)
        {
            string url = "";
            string domain = "";
            if (area == "zhengyang")
            {
                domain = "http://" + area + "zhifa.qiyedaishu.com";
                url = domain + "/Tools/" + file + ".ashx";
            }
            else if (area == "xinmi" || area=="xiping" || area == "zhoukou")
            {
                domain = "http://" + area + "zhifa.qiyedaishu.com:12580";
                url = domain + "/Tools/" + file + ".ashx";
            }
            else if (area == "huaiyang")
            {
                domain = "http://" + area + "zhifa.qiyedaishu.com:12581";
                url = domain + "/Tools/" + file + ".ashx";
            }
            else if (area == "common" || area == "dancheng" || area == "erqi" || area == "xiangcheng")
            {
                domain = "http://" + area + ".qiyedaishu.com";
                url = domain + "/Tools/" + file + ".ashx";
            }
            else
            {
                domain = "http://" + area + ".qiyedaishu.com:12580";
                url = domain + "/Tools/" + file + ".ashx";
            }
            if (file == "")
            {
                return domain;
            }
            else
            {
                return url;
            }
        }
    }
}